﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Timers;
using System.Windows.Threading;
using System.Xml.Serialization;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using client.Properties;
using System.Threading;
using System.Net.NetworkInformation;
using System.Windows.Media.Animation;
using client.Settings;
using client.Managers.Connection;

namespace client
{
    /// <summary>
    /// Main windows with all information about alerts
    /// Interaction logic for Window1.xaml
    /// </summary>
    /// 
    public partial class MainWindow : Window
    {
        System.Windows.Forms.NotifyIcon ni;
        Storyboard sbBackgr, sbReg;
        TaskbarNotifierWindow taskbarNotifier;
        public bool success;

        public MainWindow()
        {
            if (UserSettings.enableNotifyWindow != false)
            {
                taskbarNotifier = new TaskbarNotifierWindow();
            }
            try
            {
                ConfigSettings conf = new ConfigSettings();
                conf = Managers.Serialization.deserializationPref(conf);
                if (conf.getUserCultureInfo.Contains("English"))
                {
                    Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US");
                   
                }
                else if (conf.getUserCultureInfo.Contains("Русский"))
                {
                    Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("ru-RU");
                   
                }
                else if (conf.getUserCultureInfo.Contains("Українська"))
                {
                    Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("uk-UA");
                    imageCountry.Source = new BitmapImage(new Uri("Resources/Images/ukraineflag.jpg", UriKind.Relative));
                    //Uri uri = new Uri("pack://client:,,/Resources/Images/ukraine-flag.jpg");
                    //BitmapImage bitmap = new BitmapImage(uri);
                    //Image img = new Image();
                    //imageCountry.Source = bitmap;
                }
                else if (conf.getUserCultureInfo.Contains("Deutsch"))
                {
                    Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("de-DE");
                  
                }
            }
            catch
            { }        
            InitializeComponent();
            sbBackgr = ((Storyboard)FindResource("cloudBigAnimation"));
            sbReg = ((Storyboard)FindResource("regAnimation"));
            if (UserSettings.startMinimized == true)
            {
                this.WindowState = WindowState.Minimized;
                this.Hide();
                this.ShowInTaskbar = false;
            }
            this.MouseLeftButtonDown += delegate { DragMove(); };
            Microsoft.Win32.RegistryKey myKey;
            try
            {
                myKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run\");
                string loadString = (string)myKey.GetValue("GNSClient");
                if (loadString == null)
                {
                    startWithWindows.IsChecked = false;
                }
                else startWithWindows.IsChecked = true;
                myKey.Close();
            }
            catch (Exception ex)
            { }
            startMinimizedKey.IsChecked = UserSettings.startMinimized;
            enableNotifyWindowKey.IsChecked = UserSettings.enableNotifyWindow;
            Publisher.Instance.AddListener(ShowNotification);

            ni = new System.Windows.Forms.NotifyIcon();
            ni.Icon = Myres.trayiconread;
            ni.Visible = true;
            //Create a object for the context menu
            System.Windows.Forms.ContextMenuStrip TrayMenu = new System.Windows.Forms.ContextMenuStrip();
            //Add the Menu Item to the context menu
            System.Windows.Forms.ToolStripMenuItem mnuOpen = new System.Windows.Forms.ToolStripMenuItem();
            mnuOpen.Text = "Open";
            mnuOpen.Click += new EventHandler(NotifyIconOpen_Click);
            TrayMenu.Items.Add(mnuOpen);
            //
            System.Windows.Forms.ToolStripMenuItem mnuConf = new System.Windows.Forms.ToolStripMenuItem();
            mnuConf.Text = "Configure";
            mnuConf.Click += new EventHandler(NotifyIconConfigure_Click);
            TrayMenu.Items.Add(mnuConf);
            //
            System.Windows.Forms.ToolStripMenuItem mnuExit = new System.Windows.Forms.ToolStripMenuItem();
            mnuExit.Text = "Exit";
            mnuExit.Click += new EventHandler(NotifyIconExit_Click);
            TrayMenu.Items.Add(mnuExit);
            //Add the Context menu to the Notify Icon Object
            ni.ContextMenuStrip = TrayMenu;
            ni.DoubleClick +=
                delegate(object sender, EventArgs args)
                {
                    this.Show();
                    this.WindowState = WindowState.Normal;
                    this.ShowInTaskbar = true;
                    sbBackgr.Resume(this);
                };
        }

        /// <summary>
        /// Fill the information label, which shows user login
        /// </summary>
        /// <param name="userLogin">User login</param>
        /// <param name="userRegInfo">Label that contains login</param>
        private static void SetLoginLable(Label userRegInfo)
        {
            switch (UserSettings.UserName)
            {
                case "":
                    {
                        userRegInfo.Content = Languages.Language.statusLabel;
                    }
                    break;
                default: userRegInfo.Content = Languages.Language.statusLabelReady + " " + UserSettings.UserName.ToString();
                    break;
            }

        }
        /// <summary>
        /// Set visibility of the register icon
        /// </summary>
        /// <param name="visibility">true if visible, false - invisible</param>
        /// <param name="registerImage">Link to register</param>
        private static void setRegisterImage(Image registerImage, Storyboard sbReg)
        {
            if (UserSettings.UserName == "")
            {
                registerImage.Visibility = Visibility.Visible;
                sbReg.Begin();
            }
            else
            {
                registerImage.Visibility = Visibility.Hidden;
                sbReg.Stop();
            }
        }
        /// <summary>
        /// Open dialog window "Preferences"
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonPreferences_Click(object sender, RoutedEventArgs e)
        {
            Preferences pref = new Preferences();
            pref.Owner = this;
            pref.ShowDialog();
            if (pref.DialogResult.HasValue & pref.DialogResult.Value)
            {
                SetLoginLable(userRegInfo);
                setRegisterImage(registerImage, sbReg);
                Microsoft.Win32.RegistryKey myKey;
                try
                {
                    myKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run\");
                    string loadString = (string)myKey.GetValue("GNSClient");
                    if (loadString == null)
                    {
                        startWithWindows.IsChecked = false;
                    }
                    else startWithWindows.IsChecked = true;
                    myKey.Close();
                }
                catch (Exception ex)
                { }
            }
        }
        /// <summary>
        /// Starting timer after program was launched
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            setRegisterImage(registerImage, sbReg);
            SetLoginLable(userRegInfo);
        }
      

        /// <summary>
        /// Close application from taskbar
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            ni.Dispose();
            System.Windows.Application.Current.Shutdown();
        }
        /// <summary>
        /// Minimize application into tray
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void minimize_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            sbBackgr.Pause(this);
            this.ShowInTaskbar = false;
            this.WindowState = WindowState.Minimized;
            this.Hide();
        }
        /// <summary>
        /// Force update information about alerts
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void forceUpdateButton_Click(object sender, RoutedEventArgs e)
        {
            //AlertBaseFactory earthquake = new IrisFactory();
            //IAlert earthquakeAlert = earthquake.CreateEarthquakeAlert(10, 90, -90, 90, -90);
            //List<BaseAlert> baseAlerts = earthquakeAlert.CheckAlert();
            //foreach (BaseAlert ba in baseAlerts)
            //{
            //    notificationDisplay.AppendText(ba.NotificationDescription.alert_type + "\n" + ba.NotificationDescription.notification);
            //}
            //if (baseAlerts.Count == 0)
            //    notificationDisplay.AppendText("No alerts");

            success = CheckInternetConnection.IsConnectedToInternet();
            string alert = string.Empty;
            if (success)
            {
                showNotification(null);
            }
            else MessageBox.Show(Languages.Language.errCheckInet.ToString());
        }


        /// <summary>
        /// This method gets and display notifications from internet
        /// </summary>
        private void showNotification(object stateInfo)
        {
            /////!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            ///// ГОТОВЫЙ ОБЪЕКТ КОТОРЫЙ ОТПРАВЛЯТЬ НА СЕРВАК
            //client.Internet.userThreshold userThr = new client.Internet.userThreshold();
            //userThr.Temp = UserSettings.tempThreshold;
            //userThr.Pressure = UserSettings.pressureThreshold;
            /////!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            //string alert = string.Empty;
            //alert = Services.LookForAlerts(UserSettings.UserName);
            ////if (enableNotifyWindow != false)
            ////{
            //notificationDisplay.Dispatcher.Invoke((ThreadStart)delegate
            //{
            //    notificationDisplay.Document.Blocks.Clear();
            //    notificationDisplay.AppendText(alert);
            //});
        }

        /// <summary>
        /// Opens our web site
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openWebSite_Click(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://www.google.ru", null);
        }
        private void NotifyIcon_DoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left)
            {
                // Open the TaskbarNotifier
                this.taskbarNotifier.Notify();
            }
        }
        /// <summary>
        /// Open the Main Window
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NotifyIconOpen_Click(object sender, EventArgs e)
        {
            this.Show();
            this.WindowState = WindowState.Normal;
            sbBackgr.Resume(this);
        }
        /// <summary>
        /// Open preferences
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NotifyIconConfigure_Click(object sender, EventArgs e)
        {
            Preferences pref = new Preferences();
            pref.Show();
        }
        /// <summary>
        /// Close application from tray
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NotifyIconExit_Click(object sender, EventArgs e)
        {
            ni.Dispose();
            System.Windows.Application.Current.Shutdown();
        }


        private void registerImage_MouseEnter(object sender, MouseEventArgs e)
        {
            System.Diagnostics.Process.Start("http://www.google.ru", null);
        }

        protected void ShowNotification(object sender, AlertsPublisherEventArgs args)
        {
            notificationDisplay.Dispatcher.Invoke((ThreadStart)delegate
            {
                notificationDisplay.Document.Blocks.Clear();
                notificationDisplay.AppendText(args.Alerts[0].NotificationDescription.notification);
            });
        }

        private void imgQuit_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            System.Windows.Application.Current.Shutdown();
        }

        private void imgSendEmail_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            string _sendemail = ("mailto:gnsteam@hotmail.com");
            string _sendemail2 = (_sendemail + "&subject=Help me!");
            string _sendemail3 = (_sendemail2 + "&body=");
            System.Diagnostics.Process.Start(_sendemail3);
        }
    }
}
